package com.miboxlabs.esecure.provider;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicInteger;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.miboxlabs.esecure.entity.Folder;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
	private static final String DATABASE_NAME = "esecure.db";	
	private static final int DATABASE_VERSION = 1;	
	private Dao<Folder, Integer> folderDao = null;
	private static final AtomicInteger usageCounter = new AtomicInteger(0);
		
	private static DatabaseHelper helper = null;

	private DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	public static synchronized DatabaseHelper getHelper(Context context) {
		if (helper == null) {
			helper = new DatabaseHelper(context);
		}
		return helper;
	}
	
	
	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onCreate");
			TableUtils.createTable(connectionSource, Folder.class);
			
			
			Dao<Folder, Integer> dao = getFolderDao();	
			
			Folder folder = new Folder();
			folder.setName("computer LogIn");
			dao.create(folder);
			Folder  folder1= new Folder();
			folder.setName("Web LogIn");
			dao.create(folder);
			
		} catch (SQLException e) {
			
			throw new RuntimeException(e);
		} 
	}


	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
		try {
			
			TableUtils.dropTable(connectionSource, Folder.class, true);
			
			onCreate(db, connectionSource);
		} catch (SQLException e) {
		
			throw new RuntimeException(e);
		}
	}	
	
	public Dao<Folder, Integer> getFolderDao() throws SQLException {
		if (folderDao == null) {
			folderDao = getDao(Folder.class);
		}
		return folderDao;
	}
	
	
	@Override
	public void close() {
		if (usageCounter.decrementAndGet() == 0) {
			super.close();
			folderDao = null;
		}
	}
}
